//
//  CYRechargeViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/15.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYRechargeViewController.h"

#import "CYSelectCardView.h"
#import "CYPaymentAffirmView.h"

#import "CYDataAPIBankCardModel.h"

#import "CYRechargeRecordViewController.h"
#import "CYBindCardViewController.h"
#import "CYRechargeSuccessViewController.h"
#import "CYWebViewController.h"
#import "CYRechargeInProgressViewController.h"

#import "CYSMSExpireManager.h"



@interface CYRechargeViewController ()<UITextFieldDelegate>

@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UILabel *rechargeLabel;
@property(nonatomic, strong)UITextField *rechargeTextField;
@property(nonatomic, strong)UIButton *limitButton;
@property(nonatomic, strong)UIButton *submitButton;
@property(nonatomic, strong)UIButton *selectCardButton;

@property(nonatomic, strong)NSArray<CYDataAPIBankCardModel *> *cardList;
@property(nonatomic, strong)CYDataAPIBankCardModel *currentCard;

@property(nonatomic, strong)NSString *mobile_auth_code;
@property(nonatomic, strong)NSString *recharge_no;
@property(nonatomic, strong)NSNumber *lastAmount;

@property(nonatomic, assign)BOOL successed;

@end


@implementation CYRechargeViewController

- (void)close
{
    [MobClick event:UM_EVENT_0059];
    [super close];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    if(self.successed)
    {
        self.navigationController.viewControllers = @[self.navigationController.viewControllers.firstObject, self.navigationController.viewControllers.lastObject];
    }
}

- (void)loadUI
{
    self.navigationItem.title = @"充值";
    self.tableView.hidden = YES;
    
    UIButton *recordButton = [UIButton buttonWithType:UIButtonTypeSystem];
    recordButton.tintColor = HEXCOLOR(@"444444");
    [recordButton setTitle:@"充值记录" forState:UIControlStateNormal];
    recordButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [recordButton sizeToFit];
    [recordButton addTarget:self action:@selector(onRecordButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:recordButton];
    
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.topView];
    {
        self.rechargeLabel = [[UILabel alloc] init];
        self.rechargeLabel.text = @"充值金额";
        self.rechargeLabel.textColor = HEXCOLOR(@"444444");
        self.rechargeLabel.font = [UIFont systemFontOfSize:16];
        [self.rechargeLabel sizeToFit];
        [self.topView addSubview:self.rechargeLabel];
        
        self.rechargeTextField = [[TCNoActionTextField alloc] init];
        self.rechargeTextField.keyboardType = UIKeyboardTypeDecimalPad;
        [self.rechargeTextField addTarget:self.rechargeTextField action:@selector(resignFirstResponder) forControlEvents:UIControlEventEditingDidEndOnExit];
        self.rechargeTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入金额" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSForegroundColorAttributeName : HEXCOLOR(@"999999")}];
        self.rechargeTextField.delegate = self;
        self.rechargeTextField.textColor = HEXCOLOR(@"444444");
        self.rechargeTextField.font = [UIFont systemFontOfSize:16];
        [self.topView addSubview:self.rechargeTextField];
    }
    
    self.limitButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.limitButton.tintColor = APP_DEFAULT_COLOR_BLUE;
    self.limitButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [self.limitButton setTitle:@"限额说明" forState:UIControlStateNormal];
    [self.limitButton addTarget:self action:@selector(onLimitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.limitButton];
    
    self.submitButton = [UIButton cy_mainButtonWithTitle:@"确认充值"];
    [self.submitButton addTarget:self action:@selector(onSubmitButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:self.submitButton];
    
    self.selectCardButton = [[UIButton alloc] init];
    [self.selectCardButton addTarget:self action:@selector(onSelectCardButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    self.selectCardButton.hidden = YES;
    [self.contentView addSubview:self.selectCardButton];
}

- (void)layoutUI
{
    self.topView.width = self.contentView.width;
    self.topView.height = 50;
    self.topView.left = 0;
    self.topView.top = 10;
    {
        self.rechargeLabel.centerY = self.topView.height / 2;
        self.rechargeLabel.left = 20;
        
        self.rechargeTextField.width = self.topView.width - 137;
        self.rechargeTextField.height = self.topView.height;
        self.rechargeTextField.left = 117;
        self.rechargeTextField.top = 0;
    }
    
    [self.limitButton sizeToFit];
    self.limitButton.height = 36;
    self.limitButton.top = self.topView.bottom;
    self.limitButton.right = self.contentView.width - 20;
    
    self.submitButton.width = self.contentView.width - 40;
    self.submitButton.height = 44;
    self.submitButton.centerX = self.contentView.width / 2;
    self.submitButton.top = 126;
    
    self.selectCardButton.width = self.submitButton.width;
    self.selectCardButton.height = 44;
    self.selectCardButton.top = self.submitButton.bottom + 5;
    self.selectCardButton.centerX = self.submitButton.centerX;
}

- (void)loadData
{
    [self loadDataFromServer];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    if(self.cardList.count == 0)
    {
        [SVProgressHUD show];
    }
    @weakify(self);
    [CYStandardDataAPI user_queryBindBankCardWithComplete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            BOOL flag = NO;
            self.cardList = [CYDataAPIBankCardModel mj_objectArrayWithKeyValuesArray:response.content];
            for(CYDataAPIBankCardModel *model in self.cardList)
            {
                if(self.currentCard.id && [model.id isEqualToNumber:self.currentCard.id])
                {
                    flag = YES;
                    break;
                }
            }
            if(flag == NO)
            {
                self.currentCard = self.cardList.firstObject;
            }
            if(self.currentCard)
            {
                self.selectCardButton.hidden = NO;
                [self reloadCardButton];
            }
            else
            {
                self.selectCardButton.hidden = YES;
            }
            [SVProgressHUD dismiss];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)reloadCardButton
{
    NSString *cardNumber = SAFE_STRING(self.currentCard.bankCardNo);
    if(cardNumber.length < 4)
    {
        cardNumber = @"****";
    }
    else
    {
        cardNumber = [cardNumber substringFromIndex:cardNumber.length - 4];
    }
    [self.selectCardButton setAttributedTitle:[self hintButtonAttributedStringWithDesc:[NSString stringWithFormat:@"使用%@(%@)充值，", self.currentCard.bankName, cardNumber]] forState:UIControlStateNormal];
}

#pragma mark - Actions
- (void)recordAction
{
    CYRechargeRecordViewController *rechargeRecordViewController = [[CYRechargeRecordViewController alloc] init];
    [self.navigationController pushViewController:rechargeRecordViewController animated:YES];
}

- (void)limitAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/bank_info.html"];
    webViewController.defaultTitle = @"限额说明";
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)submitAction
{
    [self.view endEditing:YES];
    if(self.currentCard)
    {
        if(SAFE_STRING(self.currentCard.mobile).length != 11)
        {
            [SVProgressHUD showErrorWithStatus:@"银行卡信息错误，请更换银行卡充值"];
            return;
        }
        if(self.rechargeTextField.text.length == 0 || self.rechargeTextField.text.doubleValue <= 0)
        {
            [SVProgressHUD showErrorWithStatus:@"请输入正确的充值金额"];
            return;
        }
        NSTimeInterval seconds = [CYStandardSMSExpireManager secondsWithType:CYSMSExpireTypePayment];
        if(seconds > 0)
        {
            if(self.lastAmount && ![self.lastAmount isEqualToNumber:@(self.rechargeTextField.text.doubleValue)])
            {
                [SVProgressHUD showInfoWithStatus:[NSString stringWithFormat:@"%.0f秒后重试", seconds]];
            }
            else
            {
                [self showAffirmView];
            }
            return;
        }
        @weakify(self);
        [self smsCodeActionWithComplete:^() {
            @strongify(self);
            [self showAffirmView];
        }];
    }
    else
    {
        [self addCardAction];
    }
}

- (void)showAffirmView
{
    @weakify(self);
    CYPaymentAffirmView *view = [[CYPaymentAffirmView alloc] initWithMobile:self.currentCard.mobile];
    view.checkButton = ^(UIButton *button) {
        NSTimeInterval seconds = [CYStandardSMSExpireManager secondsWithType:CYSMSExpireTypePayment];
        if(seconds <= 0)
        {
            button.enabled = YES;
        }
        else
        {
            button.enabled = NO;
            [button setTitle:[NSString stringWithFormat:@"%.0fs后重发", seconds] forState:UIControlStateDisabled];
        }
    };
    @weakify(view);
    view.resend = ^{
        @strongify(self);
        [self smsCodeActionWithComplete:^() {
            @strongify(view);
            [view checkSeconds];
        }];
    };
    view.complete = ^(NSString *smsCode) {
        @strongify(self);
        self.mobile_auth_code = smsCode;
        [self rechargeActionWithComplete:^(BOOL inProgress){
            @strongify(self);
            @strongify(view);
            [view close];
            if(inProgress)
            {
                [self inProgressAction];
            }
            else
            {
                [self successAction];
            }
        }];
    };
    [view checkSeconds];
    [view show];
}

- (void)rechargeActionWithComplete:(void(^)(BOOL inProgress))complete
{
    if(self.mobile_auth_code.length == 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入验证码"];
        return;
    }
    [SVProgressHUD show];
    [CYStandardDataAPI user_walletRechargeWithMobile_auth_code:self.mobile_auth_code pay_way:CYDataAPIPayWayBaoFu recharge_no:self.recharge_no complete:^(CYResponse *response) {
        if(response.code == 0 || response.code == 22017)
        {
            [CYStandardSMSExpireManager resetExpireDate:[NSDate date] type:CYSMSExpireTypePayment];
            [SVProgressHUD dismiss];
            if(complete)
            {
                complete(response.code == 22017);
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)smsCodeActionWithComplete:(void(^)(void))complete
{
    [SVProgressHUD show];
    @weakify(self);
    [CYStandardDataAPI user_preWalletRechargeWithAmount:[@(self.rechargeTextField.text.doubleValue).amountString stringByReplacingOccurrencesOfString:@"," withString:@""] bank_card_no:self.currentCard.bankCardNo card_no:self.currentCard.cardNo mobile:self.currentCard.mobile pay_way:CYDataAPIPayWayBaoFu real_name:self.currentCard.realName complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            [SVProgressHUD dismiss];
            NSNumber *seconds = response.content[@"seconds"];
            if(![seconds isKindOfClass:[NSNumber class]])
            {
                seconds = @60;
            }
            [CYStandardSMSExpireManager resetExpireDate:[NSDate dateWithTimeIntervalSinceNow:seconds.doubleValue] type:CYSMSExpireTypePayment];
            self.recharge_no = response.content[@"rechargeNo"];
            self.lastAmount = @(self.rechargeTextField.text.doubleValue);
            if(complete)
            {
                complete();
            }
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:response.message];
        }
    }];
}

- (void)successAction
{
    self.successed = YES;
    CYRechargeSuccessViewController *rechargeSuccessViewController = [[CYRechargeSuccessViewController alloc] init];
    [self.navigationController pushViewController:rechargeSuccessViewController animated:YES];
}

- (void)inProgressAction
{
    self.successed = YES;
    CYRechargeInProgressViewController *rechargeInProgressViewController = [[CYRechargeInProgressViewController alloc] init];
    rechargeInProgressViewController.type = CYRechargeInProgressTypeRecharge;
    [self.navigationController pushViewController:rechargeInProgressViewController animated:YES];
}

- (void)selectCardAction
{
    [self.view endEditing:YES];
    @weakify(self);
    CYSelectCardView *view = [[CYSelectCardView alloc] initWithCardList:self.cardList title:@"选择付款方式" hasAddButton:YES];
    view.completeAction = ^(CYDataAPIBankCardModel *apiModel) {
        @strongify(self);
        self.currentCard = apiModel;
        [self reloadCardButton];
    };
    view.addCardAction = ^{
        @strongify(self);
        [self addCardAction];
    };
    [view show];
}

- (void)addCardAction
{
    [self.view endEditing:YES];
    if(self.rechargeTextField.text.length == 0 || self.rechargeTextField.text.doubleValue <= 0)
    {
        [SVProgressHUD showErrorWithStatus:@"请输入正确的充值金额"];
        return;
    }
    CYBindCardViewController *bindCardViewContoller = [[CYBindCardViewController alloc] init];
    bindCardViewContoller.type = CYBindCardTypeRecharge;
    bindCardViewContoller.willPayment = @(self.rechargeTextField.text.doubleValue);
    [self.navigationController pushViewController:bindCardViewContoller animated:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if(textField == self.rechargeTextField)
    {
        NSString *result = [textField.text stringByReplacingCharactersInRange:range withString:string];
        if(result.length == 0)
        {
            return YES;
        }
        NSString *regex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";
        NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
        return [predicte evaluateWithObject:result];
    }
    return YES;
}

#pragma mark - Control Events
- (void)onRecordButtonTouchUpInside
{
    [self recordAction];
}

- (void)onLimitButtonTouchUpInside
{
    [self limitAction];
}

- (void)onSubmitButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0060];
    [self submitAction];
}

- (void)onSelectCardButtonTouchUpInside
{
    [self selectCardAction];
}

#pragma mark - Private Method
- (NSAttributedString *)hintButtonAttributedStringWithDesc:(NSString *)desc
{
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] init];
    UIFont *font = [UIFont systemFontOfSize:14 weight:UIFontWeightRegular];
    UIColor *descColor = HEXCOLOR(@"666666");
    UIColor *contentColor = APP_DEFAULT_COLOR_BLUE;
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:desc ? desc : @"" attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : descColor}]];
    [string appendAttributedString:[[NSAttributedString alloc] initWithString:@"更换" attributes:@{NSFontAttributeName : font, NSForegroundColorAttributeName : contentColor}]];
    return string;
}

@end
